package org.csu.mall.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.csu.mall.common.CONSTANT;
import org.csu.mall.common.UniformResponse;
import org.csu.mall.entity.Category;
import org.csu.mall.persistence.CategoryMapper;
import org.csu.mall.service.ICategoryService;
import org.csu.mall.utils.UsernameUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class CategoryServiceImpl implements ICategoryService {
    private Logger logger= LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public UniformResponse<List<Category>> getCategory(Integer categoryId) {
        QueryWrapper<Category> query=new QueryWrapper<>();
        query.eq("parent_id",categoryId);
        List<Category> categoryList=categoryMapper.selectList(query);
        if(CollectionUtils.isEmpty(categoryList))
        {
            logger.info("查找子分类时，没有对应子分类");
            return UniformResponse.createForErrorMessage("查找子分类时，没有对应子分类");
        }
        return UniformResponse.createForSuccess(categoryList);
    }

    @Override
    public UniformResponse<List<Integer>> getAllChildrenCategory(Integer categoryId){
            Set<Category> categorySet = Sets.newHashSet();
            findChildrenCategory(categoryId, categorySet);
            if (categorySet.isEmpty()) {
                return UniformResponse.createForErrorMessage("无该父类");
            }
            List<Integer> categoryIdList = Lists.newArrayList();
            if (categoryId != null) {
                for (Category category : categorySet) {
                    categoryIdList.add(category.getId());
                }
            }
            return UniformResponse.createForSuccess(categoryIdList);

    }

    @Override
    public UniformResponse<List<Category>> getAllCategory() {
//        Set<Category> categorySet = Sets.newHashSet();
//        findChildrenCategory(CONSTANT., categorySet);
//        if (categorySet.isEmpty()) {
//            return UniformResponse.createForErrorMessage("无该父类");
//        }
        List<Category> categoryIdList = categoryMapper.selectList(Wrappers.<Category>query());
//        if (categoryId != null) {
//            for (Category category : categorySet) {
//                categoryIdList.add(category.getId());
//            }
//        }
        return UniformResponse.createForSuccess(categoryIdList);
    }

    @Override
    public UniformResponse<Category> addCategory(Integer parentId, String categoryName) {
        String username= UsernameUtil.getUsername("username");
        String userid= UsernameUtil.getUserId("userid");
        if(username==null){
            return UniformResponse.notLogining();
        }else {
            QueryWrapper<Category> query = new QueryWrapper<>();
            query.eq("name", categoryName);
            Category have = categoryMapper.selectOne(query);
            if (have == null) {
                Category category = new Category();
                category.setParentId(parentId);
                category.setName(categoryName);
                category.setCreateTime(LocalDateTime.now());
                category.setUpdateTime(LocalDateTime.now());
                QueryWrapper<Category> query1 = new QueryWrapper<>();
                query1.eq("parent_id", parentId);
                List<Category> categoryList = categoryMapper.selectList(query1);
                Integer sortOrder = 1;
                List<Integer> sortOrderList = new ArrayList<>();
                if (categoryList.isEmpty()) {
                    category.setSortOrder(1);
                } else {
                    for (Category category1 : categoryList) {
                        sortOrderList.add(category1.getSortOrder());
                    }
                    category.setSortOrder(Collections.max(sortOrderList) + 1);
                }

                categoryMapper.insert(category);
                return UniformResponse.createForSuccess("添加品类成功",category);
            }

            return UniformResponse.createForErrorMessage("添加品类失败");
        }
    }

    @Override
    public UniformResponse<Category> setCategoryName(Integer categoryId, String categoryName) {
        String username= UsernameUtil.getUsername("username");
        String userid= UsernameUtil.getUserId("userid");
        if(username==null){
            return UniformResponse.notLogining();
        }else {
            QueryWrapper<Category> query = new QueryWrapper<>();
            query.eq("id", categoryId);
            Category category = categoryMapper.selectOne(query);
            if (category != null) {
                category.setName(categoryName);
                category.setUpdateTime(LocalDateTime.now());
                categoryMapper.updateById(category);
                return UniformResponse.createForSuccess("更新品类名字成功",category);
            }
            return UniformResponse.createForErrorMessage("更新品类名字失败");
        }
    }

    @Override
    public UniformResponse getParentName(Integer categoryId) {
        Stack<String> namestack=new Stack<>();
        List<String> nameList=new ArrayList<>();
        Category category=categoryMapper.selectById(categoryId);
        if(category==null)
        {
           return UniformResponse.createForErrorMessage("无该子类");
        }
        namestack=findFatherCategoryName(categoryId,namestack);
        while(!namestack.empty())
        {
            String name=namestack.pop();
            nameList.add(name);
        }
        //Collections.reverse(nameList);
        return UniformResponse.createForSuccess(nameList);
    }

    private Set<Category> findChildrenCategory(Integer categoryId,Set<Category>categorySet){
        Category category=categoryMapper.selectById(categoryId);
        if(category!=null)
        {
            categorySet.add(category);
        }
        QueryWrapper<Category> query=new QueryWrapper<>();
        query.eq("parent_id",categoryId);
        List<Category> categoryList=categoryMapper.selectList(query);
        for(Category categoryItem: categoryList)
        {
            findChildrenCategory(categoryItem.getId(),categorySet);
        }
        return categorySet;
    }
    private Stack<String> findFatherCategoryName(Integer categoryId,Stack<String>nameStack)
    {
        Category category=categoryMapper.selectById(categoryId);
        if(category!=null)
        {
            nameStack.push(category.getName());
        }
        if(category.getParentId()==0)
        {
            return nameStack;
        }
        findFatherCategoryName(category.getParentId(),nameStack);
        return nameStack;
    }
}
